<?php
namespace app\money\controller;
use app\admin\common\Base;
use think\Db;
// 应收账款明细表
class Accountproceedsdetail extends Base
{
    public function index()
    {
        $data = $this->request->param();
 		$month = $this->get_month_start_to_end();
      	$this->assign('month', $month);
        if (isset($data['ajax']) && $data['ajax'] == 100) {
        	$search=[];
        	$where=[];
        	$where1=[];//防覆盖
            $page = isset($data['page']) ? $data['page'] : 1;
            $page = intval($page);
            $limit = isset($data['rows']) ? $data['rows'] : 10;
            $limit = intval($limit);
            $start = $limit * ($page - 1);

            if (isset($data['startdate']) && isset($data['enddate'])) {
	            $month = $this->get_month_start_to_end($data['startdate'], $data['enddate']);
	        } else {
	            $month = $this->get_month_start_to_end();
	        }

	     	 //备注
	        // if (isset($data['mark']) && $data['mark'] != '') {
	        //      $search['mark'] =['like',"%".$data['mark']."%"]; 
	        // }
	        //客户
	        if (isset($data['user_id']) && $data['user_id'] != '') {
	            $where['user_id']= ['in', $data['user_id']];
	        }
	         //客户类别
	     
	        if (!isset($data['customer_category_id']) || $data['customer_category_id'] == 0 || $data['customer_category_id'] == '') {
         	} else {
	            $c = Db::name('customer')->where('category_id', $data['customer_category_id'])->select();
	            $c['ids'] = implode(',', array_column($c, 'id'));
	            $where1['user_id']= ['in',$c['ids']];//客户类别
            }
	       
	        $alist=[];
 			$acc=Db::name('user_money')->where('o_way','in',[0,1,4])->where($where)->where($where1)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->distinct(true)->field('user_id')->order('user_id asc')->select();
 			foreach ($acc as $ke => &$va) {
 				$user=Db::name('customer')->where('id',$va['user_id'])->find();
            	$va['user_name']=$user['sn'].''.$user['name'];
            	$va['yu_e']=$this->user_time_money($month['month_start'],$va['user_id']);
            	$va['o_type_name']="期初余额";
            	array_push($alist, $va);

            	// *************************
            	
	            $list =  Db::name('user_money')->where('o_way','in',[0,1,4])->where($search)->where('user_id', $va['user_id'])->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->where('addtime', '>=', $month['month_start'])->where('addtime', '<=', $month['month_end'])->order('user_id asc,addtime asc,id asc')->select();
	             
	               
	          
	            $money=$va['yu_e'];
	            foreach ($list as $key => $val) {
	            	$user=Db::name('customer')->where('id',$va['user_id'])->find();
            		$val['user_name']=$user['sn'].''.$user['name'];
	                $val['add_time'] = date('Y-m-d', $val['addtime']); 
	                switch ($val['o_way']) {
						case 0:
							$val['o_type_name']="普通销售";
							break;
						case 1:
							$val['o_type_name']="销售退回";
							break;
						case 4:
							$val['o_type_name']="收款";
							break;
						
						default:
							$val['o_type_name']="其它";
							break;
					}
					$val['ying_fk']=0;
					$val['yu_fk']=0;//预付款
					
					
					
					if(in_array($val['o_way'], [4])){//收、付款单
						$aainfo=Db::name('payment')->where('sn',$val['psn'])->find();
						
						$val['saler_id']=Db::name('auth_user')->where('id',$aainfo['saler'])->value('id');
						$val['saler']=Db::name('auth_user')->where('id',$aainfo['saler'])->value('name');
						$p = Db::name('payment')->where('sn',$val['psn'])->where('id',$val['pid'])->find();
						$val['ying_fk']=0-$p['hexiao_jine'];//应付款
						$val['yu_fk']=$p['now_jine'];//预付款
						
						
					}else if (in_array($val['o_way'], [0,1])) {//销售

						if($val['o_way']==0){
							$val['ying_fk']=$val['user_price']-$val['system_price'];//应付款
						}else{
							$val['ying_fk']=$val['system_price']-$val['user_price'];//应付款
						}
						//$val['ying_fk']="200";
						$aainfo=Db::name('order')->where('sn',$val['psn'])->find();
						
						$val['saler_id']=Db::name('auth_user')->where('id',$aainfo['saler'])->value('id');
						$val['saler']=Db::name('auth_user')->where('id',$aainfo['saler'])->value('name');
					
					}
					
					$money+=floatval($val['ying_fk'])-floatval($val['yu_fk']);//余额
					$val['yu_e']=sprintf("%.2f",$money);
					$flag=0;
				
	            	//收付款人
	            	if (isset($data['staff_id']) && $data['staff_id'] != '') {
	            		$arr_p=explode(',', $data['staff_id']);
	            		if ($val['o_type_name']!='期初余额'&&!in_array($val['saler_id'], $arr_p)) {
	            			$flag+=1;
	            		}
	            	}

	            	//勾选无欠款
	            	if(isset($data['wu_qk'])&&$data['wu_qk']==1){
	                    if ($val['yu_fk']==0) {
	                   		$flag+=1;
	                    }
	                } 
	            	
            		if($flag==0){
            			array_push($alist, $val);
            		}
					
	            }
            	//**************************
 			}
            $count = count($alist);
            return $this->grid_data($alist, $count, $page, $limit);
        }
        $today=date('Y-m-d',time());
        $mon_start=date('Y-m',time()).'-01';
        $this->assign('today',$today);
        $this->assign('mon_start',$mon_start);
      
        return $this->fetch();
    }


    //账户记录--根据时间查询当前时间金额
	//$type 0包含当前时间 ，1不包含当前时间
	function user_time_money($time,$user_id)
	{
		//return 0;
		
		$list =  Db::name('user_money')->where('is_del', 0)->where('user_id', $user_id)->where('enterprise_id', $this->EnterpriseId)->where('addtime', '<', $time)->order('addtime asc,id asc')->select();
		
		$money=0;
		// //halt($list);
		foreach ($list as $key => $val) {
			//收款，销售，采购退货
			if(in_array($val['o_way'], [0,1])){
				$money+=floatval($val['account_money']);
				if($val['o_way']==0){
					$money+=floatval($val['user_price'])-floatval($val['system_price']);//应付款
				}else{
					$money+=floatval($val['system_price'])-floatval($val['user_price']);//应付款
				}
				
			}else{
				$p = Db::name('payment')->where('sn',$val['psn'])->where('id',$val['pid'])->find();
				$ying=0-$p['hexiao_jine'];//应付款
				$yu=$p['now_jine'];//预付款
				$money+=floatval($ying)-floatval($yu);
			}
		}
		return sprintf("%.2f",$money);
	}

	function user_list($where,$month)
	{
		$arr=[];
		$list1 =Db::name('order')->where($where)->where('o_type', 'in',[1,2])->where('status', 1)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->distinct(true)->field('user_id')->order('user_id asc')->select();
		$list2 =Db::name('payment')->where($where)->where('type',0)->where('status', 1)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->distinct(true)->field('user_id')->order('user_id asc')->select();
		foreach ($list1 as $key => $val) {
			array_push($arr, $val['user_id']);
		}
		foreach ($list2 as $ke => $va) {
			if (!in_array($va['user_id'], $arr)) {
				array_push($arr, $va['user_id']);
			}
		}
		
		return $arr;
	}



}
